package service

import (
	"GoProject/YUAN/projectl/model"
	"encoding/json"
	"fmt"
	"io/ioutil"
)

type CustomerService struct {
	customers   []model.Customer
	customersId int
}

func NewCustomerService() CustomerService {
	var customers []model.Customer
	customersJsonBytes, err := ioutil.ReadFile("db/customers.json")
	if err != nil {
		fmt.Println("err:", err)
	}
	json.Unmarshal(customersJsonBytes, &customers)

	return CustomerService{customers, len(customers) + 1}
}

func (cs *CustomerService) FindById(id int) int {
	index := -1
	for i := 0; i < len(cs.customers); i++ {

		if cs.customers[i].Cid == id {
			index = i
		}
	}
	return index
}

func (cs *CustomerService) FindCustomer(id int) *model.Customer {
	return &cs.customers[cs.FindById(id)]
}

func (cs *CustomerService) AddCustomer(name string, gender string, age int8, email string) {
	// 创建客户的map对象
	cs.customersId++ // 客户编号不需要输入，系统自增即可
	newCustomer := model.NewCustomer(cs.customersId, name, gender, age, email)
	// 添加客户map对象添加到客户切片中
	cs.customers = append(cs.customers, newCustomer)
}

func (cs *CustomerService) ListCustomer() []model.Customer {
	return cs.customers

}
func (cs *CustomerService) UpdateCustomer(updateCustomer *model.Customer, name string, age int8, gender string, email string) bool {

	if age != 0 {
		updateCustomer.Age = age
	}
	if name != "" {
		updateCustomer.Name = name
	}
	if gender != "" {
		updateCustomer.Gender = gender
	}
	if email != "" {
		updateCustomer.Email = email
	}

	return true

}

func (cs *CustomerService) DeleteCustomer(delIndex int) {
	cs.customers = append(cs.customers[:delIndex], cs.customers[delIndex+1:]...)
}

func (cs *CustomerService) KeepCustomers() {

	customersJsonBytes, _ := json.Marshal(cs.customers)
	err := ioutil.WriteFile("db/customers.json", customersJsonBytes, 0666)
	if err != nil {
		return
	}

}
